<?php
/**
 * Created by PhpStorm.
 * User: davin
 * Date: 14-10-19
 * Time: 下午12:03
 *
 * 用户财务资金类
 */

use LaravelBook\Ardent\Ardent;

class MemberAccountLog extends Ardent{

    protected $table = 'member_account_log';

    public static $relationsData = array(
        'member' => array(self::BELONGS_TO, 'Member', 'foreignKey' => 'member_id', 'otherKey' => 'id'),
        'order' => array(self::BELONGS_TO, 'Order', 'foreignKey' => 'order_id', 'otherKey' => 'id'),
        'operator' => array(self::BELONGS_TO, 'User', 'foreignKey' => 'operator_id', 'otherKey' => 'id'),
    );

    //操作类型
    const INCOME = 'INCOME';
    const COST = 'COST';
    const THIRD_PAY = 'THIRD_PAY';

    //账户类型
    const INTEGRAL_ACCOUNT = 'INTEGRAL_ACCOUNT';
    const SCHOOL_CARD_ACCOUNT = 'SCHOOL_CARD_ACCOUNT';
    const WEIXIN_ACCOUNT = 'WEIXIN_ACCOUNT';

    public static $operateTypes = array(
        array('id' => 0,'keyword'=>'INCOME',   'display_name'=>'入账'),
        array('id' => 1,'keyword'=>'COST',   'display_name'=>'扣款'),
        array('id' => 2,'keyword'=>'THIRD_PAY',   'display_name'=>'第三方支付'),
    );

    public static $accountTypes = array(
        array('id' => 0,'keyword'=>'INTEGRAL_ACCOUNT',   'display_name'=>'积分账户'),
        array('id' => 1,'keyword'=>'SCHOOL_CARD_ACCOUNT',   'display_name'=>'校园卡账户'),
        array('id' => 2,'keyword'=>'WEIXIN_ACCOUNT',   'display_name'=>'微信账户'),
    );


    public static $column = array(
        'member_id' => '用户昵称',
        'operate_id' => '操作者',
        'operate_type' => '操作类型',
        'account_type' => '账户类型',
        'current_money' => '当前余额(元)',
        'freeze_money' => '冻结金额(元)',
        'happen_money' => '发生金额(元)',
        'order_id' => '订单ID',
        'created_at' => '时间',
    );

    public static function getOperateTypeIDByKeyword($keyword){
        foreach(self::$operateTypes as $operateType){
            if($operateType['keyword'] == $keyword){
                return $operateType['id'];
            }
        }
        return false;
    }

    public static function getAccountTypeIDByKeyword($keyword){
        foreach(self::$accountTypes as $accountType){
            if($accountType['keyword'] == $keyword){
                return $accountType['id'];
            }
        }
        return false;
    }

    public function beforeDelete( $forced = false )
    {
        $this->errors()->add('error', '该表不允许删除信息');
        return false;
    }

    public function log($memberId, $orderId, $operateType, $operatorId, $accountType, $currentMoney, $happenMoney, $description){
        $this->member_id = $memberId;
        $this->order_id = $orderId;
        $this->operate_type = self::getOperateTypeIDByKeyword($operateType);
        $this->operator_id = $operatorId;
        $this->account_type = self::getAccountTypeIDByKeyword($accountType);
        $this->current_money = $currentMoney;
        $this->happen_money = $happenMoney;
        $this->description = $description;

        return $this->save();
    }
}
